#!/bin/bash
set -e

echo "start  create user shell" >> /tmp/user
# Confirm gitea is running
count=1
response=""
cred_path="/data/gitea/credential"
admin_username="websoft9"
admin_email="admin@mydomain.com"

while [ "$response" != "200" ]; do
  sleep 3
  response=$(curl -s -o /dev/null -w "%{http_code}" localhost:3000 || echo "Service not available")
  if [ "$response" = "200" ]; then
    echo "gitea is runing"
    break
  fi
  count=$((count+1))
  if [ $count -gt 60 ]; then
    echo "gitea is not runing"
    break
  fi
done

if [ -e "$cred_path" ]; then
  echo "File $cred_path exists. Exiting script."
  exit 0
fi

echo "Create admin credential by admin cli"
su -c "
    if gitea admin user list | grep -q '$admin_username'; then
        echo 'User already exists.'
        exit 0
    else
        gitea admin user create --admin --username '$admin_username' --random-password --email '$admin_email' > /tmp/credential
        touch /data/gitea/create_user 2>/dev/null
    fi
" git

if [ -f /data/gitea/create_user ]; then
    echo "Read credential from tmp"
    username=$(grep -o "New user '[^']*" /tmp/credential | sed "s/New user '//")
    if [ -z "$username" ] || [ "$username" != "websoft9" ]; then
      echo "username is not websoft9, exit"
    fi
    password=$(grep -o "generated random password is '[^']*" /tmp/credential | sed "s/generated random password is '//")
    rm -rf /tmp/credential

    echo "Save to credential"
    json="{\"username\":\"$admin_username\",\"password\":\"$password\",\"email\":\"$admin_email\"}"
    echo "$json" > "$cred_path"
fi
